package com.njsoft.bodyawakening.utils;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.text.TextUtils;

import java.net.URLEncoder;

/**
 * author: Cuiernao
 * date:   On 2018/11/7
 */
public class WhatAppUtils {

    public static boolean sendWhatsApp(Context ctx, String text) {
        boolean sendOk = false;
        if (checkApkExist(ctx, "com.whatsapp")) {
            Intent vIt = new Intent("android.intent.action.SEND");
            vIt.setPackage("com.whatsapp");
            vIt.setType("text/plain");
            if (!TextUtils.isEmpty(text)) {
                vIt.putExtra(Intent.EXTRA_TEXT, text);
                vIt.putExtra(Intent.EXTRA_SUBJECT, "Subject");
            }
            ctx.startActivity(vIt);
            sendOk = true;
        }
        return sendOk;
    }

    private static boolean checkApkExist(Context ctx, String packageName) {
        if (packageName == null || "".equals(packageName))
            return false;
        try {
            ApplicationInfo info = ctx.getPackageManager().getApplicationInfo(packageName,
                    PackageManager.GET_UNINSTALLED_PACKAGES);
            if (info != null) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    public static void sendWhatsApp(Context context, String phone, String message) {
        PackageManager packageManager = context.getPackageManager();
        Intent i = new Intent(Intent.ACTION_VIEW);

        try {
            String url = "https://api.whatsapp.com/send?phone=" + phone + "&text=" + URLEncoder.encode(message, "UTF-8");
            i.setPackage("com.whatsapp");
            i.setData(Uri.parse(url));
            if (i.resolveActivity(packageManager) != null) {
                context.startActivity(i);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
